require 'Common/define'
require 'Logic/Config'
require 'Common/functions'

UICharactorInfoHeroLink = {};
HelperFunc.SetUIEnv(UICharactorInfoHeroLink)
local this = UICharactorInfoHeroLink;

this.LuaBehaviour = nil;

this.hasInit = false;

this.txtLinkCountText = nil;
this.itemHeroMain = nil;
this.tableHeroLink = {};
this.tableLinkLine = {};

this.objSelectGroup = nil;
---@type FairyGUI.GList
--this.objHeroSelectParent;

this.btnCloseBtn = nil;
this.listHero = nil
this.curSelectIndex = nil
this.lastSelectIndex = nil
this.lastObj = nil
this.btnCloseSelect = nil
this.btnCloseSelect2 = nil
this.btnSure = nil

this.heroLinkInfo = nil;
this.curSelectOrder = nil;
this.curSelectHeroId = nil;
this.curSelectHeroGo = nil;
this.interevalTime =0;
this.timer = nil;
this.ownerHeroList = {}

function UICharactorInfoHeroLink.Init(type)--todo 应该小写 暂时先大写
    this.heroType = tonumber(type or 1);
    interevalTime = G.dataTable["t_global"]["58"].f_int_value;
    local name,package = getUIName(PanelResNames.UICharactorInfoHeroLink);
    panelMgr:ShowUI(name,package, this.onCreate, Config.useLocalUI);

end
---@param obj FairyGUI.GComponent
function UICharactorInfoHeroLink.onCreate(obj)
    if not hasInit then
        hasInit = true;
        txtLinkCountText = obj:GetChild("link_num")
        btnCloseBtn = obj:GetChild("CloseBtn")
        btnBlackBg = obj:GetChild("BlackBg")
        objSelectGroup = obj:GetController("ctrlSelectGroup")
        this.linkLevel = obj:GetChild("linkLevel")

        local root = obj:GetChild("heroList")
        this.classLevel = obj:GetChild("classLevel")
        local ctrSelectSchool = root:GetController("ctrlShow")
        ctrSelectSchool.selectedIndex = 1
        this.ctrlHeroType = obj:GetController("type")
        this.levelTypeController = obj:GetController("levelType")

        btnSure = root:GetChild("btnSure")
        btnCloseSelect = root:GetChild("BackBtn")
        btnCloseSelect2 = root:GetChild("btnClose")
        listHero = root:GetChild("itemGrid")
        listHero.itemRenderer = this.UpdateOneElement
        
        itemHeroMain = this.createHeroLink(obj:GetChild("iconMy"));
        tableHeroLink = {};
        for i = 1, 8 do
            local data = this.createHeroLink(obj:GetChild("icon_"..i));
            table.insert(tableHeroLink,data);
        end

        tableLinkLine ={};
        for i = 1, 8 do
            table.insert(tableLinkLine,obj:GetController("line"..i));
        end

        this.addEvent();
    end
    this.resetData();
end

--- 选择要绑定链接的英雄卡
function UICharactorInfoHeroLink.UpdateOneElement(index, obj)
    index = index + 1
    local heroInfo = ownerHeroList[index]
    local HeadRectDrawItem = CtrlManager.GetCtrl(PanelNames.HeadRectDrawItem);
    if HeadRectDrawItem ~= nil then
        HeadRectDrawItem.initData(obj, heroInfo);
    end
    -- 事件侦听
    obj.onClick:Clear()
    obj.onClick:Add(function()
        this.OnClickHeroPos(obj, heroInfo.partnerId, index)
    end)
end
function UICharactorInfoHeroLink.OnClickHeroPos(obj, parnetId, index)
    curSelectIndex = index
    if lastSelectIndex ~= curSelectIndex then
        if lastObj then
            local tmpCtr = lastObj:GetController("gou")
            tmpCtr.selectedIndex = 0
        end
        lastObj = obj
        lastSelectIndex = curSelectIndex

        local ctrlGou = obj:GetController("gou")
        ctrlGou.selectedIndex = 1

        curSelectHeroId = parnetId
    end
end

function UICharactorInfoHeroLink.InitlizeData()
    if lastObj then
        local tmpCtr = lastObj:GetController("gou")
        tmpCtr.selectedIndex = 0
    end
    curSelectIndex = nil
    lastSelectIndex = nil
    lastObj = nil
end

function UICharactorInfoHeroLink.addEvent()
    btnCloseBtn.onClick:Add(this.onClickClose)
    btnBlackBg.onClick:Add(this.onClickClose)
    btnCloseSelect.onClick:Add(this.onClickCloseSelect)
    btnCloseSelect2.onClick:Add(this.onClickCloseSelect)
    btnSure.onClick:Add(this.onClickConfirmSelect)
    this.ctrlHeroType.onChanged:Add(this.ctrlHeroTypeChanged)
end

function UICharactorInfoHeroLink.removeEvent()
    btnCloseBtn.onClick:Clear()
    btnBlackBg.onClick:Clear()
    btnCloseSelect.onClick:Clear()
    btnCloseSelect2.onClick:Clear()
    btnSure.onClick:Clear()
    this.ctrlHeroType.onChanged:Clear()
end

function UICharactorInfoHeroLink.LocalListenEvent()
    ListenEvent(Config.EventType.Fresh_HeroLink,this.resetData);
    ListenEvent(Config.EventType.ShowLinkInResult,this.ShowLinkInResult)
end

function UICharactorInfoHeroLink.LocalCloseEvent()
    CloseEvent(Config.EventType.Fresh_HeroLink,this.resetData);
    CloseEvent(Config.EventType.ShowLinkInResult,this.ShowLinkInResult);
end

function UICharactorInfoHeroLink.OnDestroy()
    tableHeroLink = {};
    hasInit = false;
    this.removeEvent();
end

function UICharactorInfoHeroLink.OnEnable()
    this.LocalListenEvent();
end

function UICharactorInfoHeroLink.OnDisable()
    this.LocalCloseEvent();
end

function UICharactorInfoHeroLink.createHeroLink(obj)
    local data ={};
    data["gameObj"] = obj;
    data["timeText"] = obj:GetChild("TimeText")
    data["LockText"] = obj:GetChild("LockText")
    data["level"] = obj:GetChild("level")
    data["typeController"] = obj:GetController("type");
    data["head"] = obj:GetChild("hero");
    data["redDot"] = obj:GetChild("UIRedDots");
    data["speed"] = obj:GetChild("speed");
    data["button"] = obj:GetChild("button");
    return data;
end

function UICharactorInfoHeroLink.resetData()
    curSelectOrder = 0;
    curSelectHeroId = 0;
    curSelectHeroGo = nil;
    if this.ctrlHeroType then
        this.ctrlHeroType.selectedIndex = this.heroType;
    end
    if this.heroType ~= nil then
        heroLinkInfo = logicMgr.HeroLinkManager.getLinkInfosByType(this.heroType);
        this.refresh();
    end
end

function UICharactorInfoHeroLink.refresh()
--刷新函数
    if heroLinkInfo == nil then
        heroLinkInfo = {};
        heroLinkInfo.slotInfos = {};
    end
    this.refreshStateSecond();
    objSelectGroup.selectedIndex = 0;
    local linkCount = #heroLinkInfo.slotInfos;
    for i = 1, #tableHeroLink  do
        tableHeroLink[i].typeController.selectedIndex = 3;
    end
    for i = 1, #tableLinkLine  do
        tableLinkLine[i].selectedIndex = 0;
    end
    --itemHeroMain.typeController.selectedIndex = 3;
    --local level = 0
    local ctrlItem = CtrlManager.GetCtrl(PanelNames.HeadRectItem);
    --if ctrlItem ~= nil then
    --    local data = {};
    --    local hero = logicMgr.HeroManager.getHeroDatabyPartnerId(heroLinkInfo.mainHeroId,true);
    --    if hero ~= nil then
    --        data.star = hero.star;
    --        data.icon = hero.icon;
    --        data.partnerId = hero.partnerId;
    --        data.quality = hero.quality;
    --        data.type = hero.type;
    --        itemHeroMain.typeController.selectedIndex = 1;
    --        ctrlItem.initData(itemHeroMain.head, data);
    --        level = hero.level
    --        if logicMgr.HeroLinkManager.IsTopLevelOpen() then
    --            level = HeroLinkManager.GetTopLevel()
    --        end
    --        itemHeroMain.level.text = string.format(getLanguage("Level"), level)
    --    else
    --        itemHeroMain.typeController.selectedIndex = 0;
    --        itemHeroMain.level.text = "暂无";
    --    end
    --    itemHeroMain.head.touchable = false;
    --end
    local sumLevel = logicMgr.HeroLinkManager.GetHeroLevel();
    local level = sumLevel;
    if logicMgr.HeroLinkManager.IsTopLevelOpen() then
        level = HeroLinkManager.GetTopLevel()
    end
    --local lev = logicMgr.HeroLinkManager.GetMiniLevlBySchool(this.heroType);
    this.linkLevel.text = string.format(getLanguage("Level"), sumLevel)
    this.classLevel.text = string.format(getLanguage("Level"), level)

    if sumLevel >= level or HeroLinkManager.IsTopLevelOpen() then
        this.levelTypeController.selectedIndex = 0;
        this.maxLevel=level
    else
        this.levelTypeController.selectedIndex = 0;
        this.maxLevel=sumLevel
    end
    local redDots = false;
    if RedDotsHeroLinkHandler.getFlag(this.heroType) == Config.RedDotsFlagState.Needful then
        redDots = true;
    end
    linkCount = linkCount < #tableHeroLink and linkCount or #tableHeroLink;
    local linkedCount = 0;
    for i = 1, linkCount do
        tableHeroLink[i].speed.onClick:Clear();
        local isHave = heroLinkInfo.slotInfos[i].partnerId ~= nil and #heroLinkInfo.slotInfos[i].partnerId > 0;
        local isUnLock = nil
        if heroLinkInfo.slotInfos[i].lockType == 1 then
            isUnLock = heroLinkInfo.slotInfos[i].unLock <= logicMgr.MapManager.getMapId()
        else
            local count = logicMgr.HeroLinkManager.IsNotLockByQuality(heroLinkInfo.slotInfos[i]["type"],heroLinkInfo.slotInfos[i].lockQuality[2])
            isUnLock = heroLinkInfo.slotInfos[i].lockQuality[1] <= count
        end
        local leftTime = this.getLeftTime(heroLinkInfo.slotInfos[i]);
        if leftTime > 0 then
            tableHeroLink[i].typeController.selectedIndex = 2;
            tableHeroLink[i].timeText.text = timeToTimeFormat(leftTime);
            tableHeroLink[i].speed.onClick:Add(function ()
                this.showBuySpeed(i);
            end);
        elseif not isUnLock then
            tableHeroLink[i].typeController.selectedIndex = 3;
            if heroLinkInfo.slotInfos[i].lockType == 1 then
                local data = MapManager.GetMapcfgByID(heroLinkInfo.slotInfos[i].unLock);
                if data ~= nil then
                    tableHeroLink[i].LockText.text = string.format("%d-%d关解锁", data.f_ChapterId, data.f_StageNum);
                else
                    tableHeroLink[i].LockText.text = "--";
                end
            else
                tableHeroLink[i].LockText.text = string.format(getLanguage("LevelChainUnlockTips1"),heroLinkInfo.slotInfos[i].lockQuality[1],
                        EnumConst.StarType[heroLinkInfo.slotInfos[i].lockQuality[2]/10] )
            end
        elseif isHave then
            if ctrlItem~=nil then
                local data ={};
                linkedCount = linkedCount+1;
                tableHeroLink[i].typeController.selectedIndex = 1;
                tableLinkLine[i].selectedIndex = 1;
                local partnerId = heroLinkInfo.slotInfos[i].partnerId
                local hero = logicMgr.HeroManager.getHeroDatabyPartnerId(partnerId,true);
                data.star = hero.star;
                data.icon = hero.icon;
                data.partnerId = hero.partnerId;
                data.quality = hero.quality;
                data.type = hero.type;
                data.level = HeroManager.getHeroShowLevelByPartnerId(partnerId);
                ctrlItem.initData(tableHeroLink[i].head,data,LuaBehaviour);
                tableHeroLink[i].head.onClick:Clear();
            end
        else
            tableHeroLink[i].typeController.selectedIndex = 0;
        end
        tableHeroLink[i].button.onClick:Clear();
        tableHeroLink[i].button.onClick:Add(function () this.onClickOpenSelect(i) end);
        tableHeroLink[i].redDot.visible = redDots;
    end
    --txtLinkCountText.text = "已链接"..linkedCount.."/"..linkCount;
    if timer == nil then
        timer = utimer.timeCall(this.refreshStateSecond, 1000, -1);
    end
end

function UICharactorInfoHeroLink.showBuySpeed(index)
    local num = ItemManager.getBagNumByTableID(1);
    if num < G.dataTable["t_global"][tostring(195)].f_int_value then
        UISysTips.AddMsg(getLanguage("Character_Tips7"));
        return ;
    end
    local pop = CtrlManager.GetCtrl(PanelNames.UICommonPop);
    pop.Init("30", function(b)
        if b then
            heroLinkHandler.sendClearSlotCd(index, this.heroType)
        end
    end, G.dataTable["t_global"][tostring(195)].f_int_value);
end

function UICharactorInfoHeroLink.refreshStateSecond()
    if heroLinkInfo == nil then
        return ;
    end
    local linkCount = #heroLinkInfo.slotInfos< #tableHeroLink and #heroLinkInfo.slotInfos or #tableHeroLink;
    for i = 1, linkCount do
        local leftTime = this.getLeftTime(heroLinkInfo.slotInfos[i]);

        tableHeroLink[i].gameObj.visible = true
        
        if leftTime>0 then
            tableHeroLink[i].head.visible = false
            tableHeroLink[i].timeText.visible = true
            tableHeroLink[i].timeText.text = timeToTimeFormat(leftTime);
        else
            tableHeroLink[i].head.visible = true
            tableHeroLink[i].timeText.visible = false
        end
    end
end

function UICharactorInfoHeroLink.refreshSelectSv()
    local heroList = logicMgr.HeroManager.getOwnerHeroList(false);
    table.clear(ownerHeroList)
    for i = #heroList, 1, -1 do
        if heroList[i].type == heroLinkInfo.type and not logicMgr.HeroLinkManager.isInLink(heroList[i].partnerId,true) then
            table.insert(ownerHeroList,heroList[i])
        end
    end
end

function UICharactorInfoHeroLink.onClickClose()
    if this.timerRecycle then
        utimer.remove(this.timerRecycle)
        this.timerRecycle = nil
    end
    closeUI(PanelNames.UICharactorInfoHeroLink);
end

function UICharactorInfoHeroLink.onClickCloseSelect()
    curSelectOrder =0;
    curSelectHeroId =0;
    curSelectHeroGo = nil;
    objSelectGroup:SetSelectedIndex(0)
end

function UICharactorInfoHeroLink.onClickOpenSelect(order)
    local slotInfo = heroLinkInfo.slotInfos[order];
    if slotInfo.lockType == 1 then
        if slotInfo.unLock > logicMgr.MapManager.getMapId() then
            local data = MapManager.GetMapcfgByID(slotInfo.unLock);
            if data ~= nil then
                UISysTips.AddMsg(string.format("通过%d-%d关解锁", data.f_ChapterId, data.f_StageNum));
            end
            return;
        end
    else
        local count = logicMgr.HeroLinkManager.IsNotLockByQuality(slotInfo["type"],slotInfo.lockQuality[2])
        local isUnLock = slotInfo.lockQuality[1] <= count
        if not isUnLock then
            UISysTips.AddMsg(string.format(getLanguage("LevelChainUnlockTips2"),slotInfo.lockQuality[1],
                    EnumConst.StarType[slotInfo.lockQuality[2]/10] ))
            return
        end
    end
    if this.getLeftTime(slotInfo) > 0 then
        UISysTips.AddMsg("冷却时间未到");
        return;
    end
    
    if slotInfo.partnerId == nil or #slotInfo.partnerId==0 then
        objSelectGroup:SetSelectedIndex(1)
        curSelectOrder =order;
        curSelectHeroId =0;
        curSelectHeroGo = nil;
        this.refreshSelectSv();
        this.InitlizeData()
        listHero.numItems = #ownerHeroList
    else
        local hero = logicMgr.HeroManager.getHeroDatabyPartnerId(slotInfo.partnerId,true);
        UICommonPop.Init(16,function (flag)
            if flag then
                heroLinkHandler.sendRemoveParnetLink(order,slotInfo.partnerId);
                local data = {};
                data[EnumConst.EquipPartEnum.HAND] = 0;
                data[EnumConst.EquipPartEnum.HEAD] = 0;
                data[EnumConst.EquipPartEnum.BODY] = 0;
                data[EnumConst.EquipPartEnum.LEG] = 0;
                equipHandler.sendOneKeyWearOrUnWear(slotInfo.partnerId, data);
            end
        end,hero.name);
    end
end

--- 选择要链接到智慧树上的英雄卡（当前职业，且除了已经在智慧之链上的卡）
function UICharactorInfoHeroLink.onClickConfirmSelect()
    if curSelectHeroId == nil or curSelectHeroId ==0 then
        return;
    end
    local slotInfo = heroLinkInfo.slotInfos[curSelectOrder];
    if slotInfo == nil then
        return;
    end
    if slotInfo.unLock > logicMgr.MapManager.getMapId() then
        return;
    end
    if logicMgr.HeroLinkManager.isInLink(curSelectHeroId,true) then
        return;
    end
    if this.getLeftTime(slotInfo)>0 then
        UISysTips.AddMsg("冷却时间未到");
        return;
    end
    if logicMgr.HeroManager.GetHeroLevel(curSelectHeroId) > 1 then
        partnerHandler.sendPartnerReset(curSelectHeroId); -- 先重生
    end
    heroLinkHandler.sendAddParnetLink(curSelectOrder,curSelectHeroId);
    this.savePartnerId=curSelectHeroId

end
function UICharactorInfoHeroLink.ShowLinkInResult()
    local result={}
    result.maxLevel=this.maxLevel
    result.partnerId=this.savePartnerId
    showUI(PanelNames.UILinkInResult,result)
end
function UICharactorInfoHeroLink.getLeftTime(slotInfo)
    return interevalTime -(Config.serverTime/1000 - slotInfo.lastRemoveTime);
end

function UICharactorInfoHeroLink.ctrlHeroTypeChanged()
    this.heroType = this.ctrlHeroType.selectedIndex;
    this.resetData()
end


return UICharactorInfoHeroLink;
